<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Goods\Controller;

use Admin\Controller\AdminActionController;
use Admin\Data\Common;
use Doctrine\ORM\EntityManager;
use Goods\Entity\Goods;
use Goods\Entity\GoodsClass;
use Goods\Entity\GoodsInClass;
use Goods\Form\GoodsClassForm;
use Goods\Service\GoodsBrandInClassManager;
use Goods\Service\GoodsClassManager;
use Goods\Service\GoodsInClassManager;
use Laminas\Mvc\I18n\Translator;
use Laminas\View\Model\JsonModel;
use Laminas\View\Model\ViewModel;

class GoodsClassController extends AdminActionController
{
    private $translator;
    private $entityManager;
    private $goodsClassManager;
    private $goodsInClassManager;
    private $goodsBrandInClassManager;

    public function __construct(
        Translator $translator,
        EntityManager $entityManager,
        GoodsClassManager $goodsClassManager,
        GoodsInClassManager $goodsInClassManager,
        GoodsBrandInClassManager $goodsBrandInClassManager
    )
    {
        $this->translator       = $translator;
        $this->entityManager    = $entityManager;
        $this->goodsClassManager= $goodsClassManager;
        $this->goodsInClassManager = $goodsInClassManager;
        $this->goodsBrandInClassManager = $goodsBrandInClassManager;
    }

    /**
     * 商品分类列表
     * @return array|\Laminas\View\Model\ViewModel
     */
    public function indexAction()
    {
        $goodsClass = $this->entityManager->getRepository(GoodsClass::class)->findClassList();
        $classList  = Common::adminGoodsClass($goodsClass);

        return ['class' => $classList];
    }

    /**
     * 添加商品分类
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\Common\Persistence\Mapping\MappingException
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function addAction()
    {
        $type = $this->getRequest()->getQuery('type', '');

        $form = new GoodsClassForm();
        $form->get('classTopId')->setValueOptions($this->goodsPlugin()->classListOptions());
        $form->get('classTagGroup')->setValueOptions($this->goodsPlugin()->tagGroupOptions('', false));

        if($this->getRequest()->isPost()) {
            $data = array_merge_recursive(
                $this->getRequest()->getPost()->toArray(),
                $this->getRequest()->getFiles()->toArray()
            );
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();

                $this->goodsClassManager->addGoodsClass($data);

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('分类 %s 添加成功!'), $data['className']), $this->translator->translate('商品分类'));

                return $this->redirect()->toRoute('goods-class');
            }
        }

        if($type == 'addMore') $form->get('className')->setAttributes(['type' => 'textarea', 'rows' => 6, 'placeholder' => $this->translator->translate('可同时添加多个分类，一行一个')]);

        return ['form' => $form, 'type' => $type];
    }

    /**
     * 编辑商品分类
     * @return array|\Laminas\Http\Response
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function editAction()
    {
        $classId = (int) $this->params()->fromRoute('id', -1);

        $classInfo = $this->entityManager->getRepository(GoodsClass::class)->findOneByClassId($classId);
        if($classInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该分类不存在!'));
            return $this->redirect()->toRoute('goods-class');
        }

        $form = new GoodsClassForm($this->entityManager, $classInfo);
        $form->get('classTopId')->setValueOptions($this->goodsPlugin()->classListOptions());
        $form->get('classTagGroup')->setValueOptions($this->goodsPlugin()->tagGroupOptions('', false));

        if($this->getRequest()->isPost()) {
            $data = array_merge_recursive(
                $this->getRequest()->getPost()->toArray(),
                $this->getRequest()->getFiles()->toArray()
            );
            $form->setData($data);
            if ($form->isValid()) {
                $data = $form->getData();

                $this->goodsClassManager->editGoodsClass($data, $classInfo);

                $this->adminCommon()->addOperLog(sprintf($this->translator->translate('分类 %s 编辑成功!'), $data['className']), $this->translator->translate('商品分类'));

                return $this->redirect()->toRoute('goods-class');
            }
        } else {
            $valueArray = $classInfo->valuesArray();
            $valueArray['classTagGroup'] = unserialize($valueArray['classTagGroup']);
            $form->setData($valueArray);
        }

        $query      = $this->entityManager->getRepository(GoodsInClass::class)->findClassInGoods(['class_id' => $classId]);
        $paginator  = $this->adminCommon()->shopPaginator($query, 1);

        return ['form' => $form, 'classInfo' => $classInfo, 'goodsList' => $paginator];
    }

    /**
     * 删除商品分类
     * @return mixed
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteAction()
    {
        if(!$this->adminCommon()->validatorCsrf()) return $this->adminCommon()->toReferer();

        $classId = (int) $this->params()->fromRoute('id', -1);

        $classInfo = $this->entityManager->getRepository(GoodsClass::class)->findOneByClassId($classId);
        if($classInfo == null) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该分类不存在!'));
            return $this->adminCommon()->toReferer();
        }

        $subClassInfo = $this->entityManager->getRepository(GoodsClass::class)->findOneBy(['classTopId' => $classId]);
        if($subClassInfo) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('该分类下存在分类，不能删除!'));
            return $this->adminCommon()->toReferer();
        }

        $goodsInfo = $this->entityManager->getRepository(Goods::class)->findOneBy(['classId' => $classId]);
        if($goodsInfo) {
            $this->flashMessenger()->addWarningMessage($this->translator->translate('商品里有该分类作为主分类的商品存在，不能删除!'));
            return $this->adminCommon()->toReferer();
        }

        $this->goodsClassManager->deleteGoodsClass($classInfo);
        $this->adminCommon()->deleteImage($classInfo->getClassImage());
        $this->goodsInClassManager->delClassGoods($classId);
        $this->goodsBrandInClassManager->delGoodsBrandInClassId($classId);

        $this->adminCommon()->addOperLog(sprintf($this->translator->translate('分类 %s 删除成功!'), $classInfo->getClassName()), $this->translator->translate('商品分类'));

        return $this->adminCommon()->toReferer();
    }

    /**
     * 批量处理排序
     * @return mixed
     * @throws \Doctrine\Common\Persistence\Mapping\MappingException
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function updateAllSortAction()
    {
        if($this->getRequest()->isPost()) {
            $data = $this->params()->fromPost();
            if(!empty($data['select_id'])) {
                $this->goodsClassManager->updateAllClassSort($data);

                $this->adminCommon()->addOperLog($this->translator->translate('批量排序处理成功!'), $this->translator->translate('商品分类'));
            }
        }

        return $this->adminCommon()->toReferer();
    }

    /**
     * 分类商品的分页ajax显示
     * @return array
     */
    public function ajaxClassGoodsAction()
    {
        $view = new ViewModel();
        $view->setTerminal(true);

        $classId = (int) $this->params()->fromRoute('id', -1);
        $page = (int) $this->params()->fromQuery('page', 1);
        $query      = $this->entityManager->getRepository(GoodsInClass::class)->findClassInGoods(['class_id' => $classId]);
        $paginator  = $this->adminCommon()->shopPaginator($query, $page);

        return $view->setVariables(['classId' => $classId, 'goodsList' => $paginator]);
    }

    /**
     * 更新单个分类商品信息
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function updateClassGoodsAction()
    {
        $message= $this->translator->translate('更新失败!');
        $inId   = (int) $this->request->getPost('inId', 0);
        $classGoodsSort = (int) $this->request->getPost('classGoodsSort', 1);
        $classGoodsRecommend = in_array($this->request->getPost('classGoodsRecommend'), [0, 1]) ? $this->request->getPost('classGoodsRecommend') : 0;

        $inClassGoods = $this->entityManager->getRepository(GoodsInClass::class)->findOneByInId($inId);
        if($inClassGoods) {
            $this->goodsInClassManager->updateInClassGoods(['classGoodsSort' => $classGoodsSort, 'classGoodsRecommend' => $classGoodsRecommend], $inClassGoods);
            $message = $this->translator->translate('更新成功!');
        }
        return new JsonModel(['msg' => $message]);
    }

    /**
     * 删除商品分类中的商品
     * @return JsonModel
     * @throws \Doctrine\ORM\ORMException
     * @throws \Doctrine\ORM\OptimisticLockException
     */
    public function deleteClassGoodsAction()
    {
        $inId = (int) $this->params()->fromRoute('id', -1);
        $inClassGoods = $this->entityManager->getRepository(GoodsInClass::class)->findOneByInId($inId);
        if($inClassGoods == null) return new JsonModel(['msg' => $this->translator->translate('该分类商品不存')]);

        //当其为主分类商品时，不能删除
        $goodsInfo = $this->entityManager->getRepository(Goods::class)->findOneBy(['goodsId' => $inClassGoods->getGoodsId(), 'classId' => $inClassGoods->getClassId()]);
        if($goodsInfo != null) return new JsonModel(['msg' => $this->translator->translate('不能在此进行主分类商品删除，请到编辑商品中调整主分类后，再次删除!')]);

        $this->goodsInClassManager->delInClassGoods($inClassGoods);
        return new JsonModel(['state' => 'ok']);
    }
}